import SendAudit from "@/components/custorder/pengding/SendAudit";
import Audit from "@/components/custorder/pengding/Audit";
import DoCommonTask from "@/components/custorder/pengding/DoCommonTask";
import GenerateQuotations from "@/components/custorder/pengding/GenerateQuotations";
import GenerateQuotationList from "@/components/custorder/pengding/GenerateQuotationList";
import GenerateBillList from "@/components/custorder/pengding/GenerateBillList";
import AcctBalanceBill from "@/components/custorder/pengding/AcctBalanceBill";
import AuditRecords from "@/components/custorder/examine/AuditRecords";
import Resources from "@/components/custorder/examine/Resources";
import TariffInformation from "@/components/custorder/examine/TariffInformation";
import UploadIdeaFiles from "@/components/custorder/examine/UploadIdeaFiles";
import CustOrderService from "@/api/order/CustOrderService";
import proInfo from "@/components/custorder/pengding/proInfo";
import { mapState, mapGetters, mapActions } from "vuex";
import OrderService from "@/api/order/OrderService.js";
import OrderFiles from "@/components/custorder/OrderFiles";
export default {
  name: "OrderItemCard",
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      lookListData: [
        { title: "审核记录", content: "AuditRecords" },
        { title: "资源情况", content: "Resources" },
        { title: "报价单", content: "GenerateQuotationList" },
        { title: "预收费单", content: "GenerateBillList" },
        { title: "决算单", content: "AcctBalanceBill" },
        { title: "项目信息", content: "proInfo" },
        { title: "一次性调查信息", content: "" },
        { title: "附件", content: "OrderFiles" },
        { title: "资费情况", content: "TariffInformation" },
        { title: "接口前置校验", content: "" },
        { title: "查看IP信息", content: "" },
      ],
      sysdate: this.$util.dateFormat(new Date(), "yyyy-MM-dd"),
      isContent: { ODKInfo: {}, CTOInfo: {}, title: "", content: "" },
      pendItemVisible: false,
      // pendingListData: [{ title: "需求单审核", content: "Audit" },{ title: "需求单送审", content: "SendAudit" }],
      pendingListData: []
    };
  },
  components: {
    Audit,
    SendAudit,
    DoCommonTask,
    GenerateQuotations,
    GenerateBillList,
    Resources,
    AuditRecords,
    TariffInformation,
    AcctBalanceBill,
    proInfo,
    UploadIdeaFiles,
    GenerateQuotationList,
    OrderFiles
  },
  computed: {
    ...mapState("user", ["user"]),
    ...mapGetters(["conditions"]),
    custOrderRaidoA: {
      get() {
        return this.$store.state.orders.custOrderRaidoA;
      },
      set(value) {
        this.$store.commit("orders/SET_CUST_ORDER_RADIOA", value);
      },
    },
  },
  methods: {
    uploadFun(item){
      this.isContent = {
        title: '上传电子档案',
        CTOInfo: item,
        ODKInfo: {level:'order'},
        content: 'UploadIdeaFiles',
        width: '90%',
        top: '5vh'
      };
      this.pendItemVisible = true;
    },
    dateFormat(date){
      return this.$util.dateFormat(date, "yyyy-MM-dd")
    },
    ...mapActions("orders", ["qryPendingOrderList"]),
    // 待处理显示时事件
    async dealTaskEvent(item) {
      // if(item.statusCd=='401400'){
      //     return false;
      // }
      let { custSoNumber, orderAuditId, custId } = item;
      let usersMsg = {
            acceptUserId: this.user.staffId,
            acceptUserOrg: this.user.orgId,
            systemUserId: this.user.acctId,
            dealType: 1,
            custId: custId
          },
          allprms = { custSoNumber, orderAuditId, ...usersMsg };
      const result = await CustOrderService.queryCustOrderDealTask(allprms);
      if (result.meta.resultCode == "0") {
        if (result.meta.orderDealTasks.length <= 0) {
          allprms.dealType = 234;
          const result2 = await CustOrderService.queryCustOrderDealTask(allprms);
          if (result2.meta.orderDealTasks.length > 0) {
            this.pendingListData = [
              { title: "转销售品处理", content: "toSalesDeal", CTOInfo: item },
            ];
          } else {
            this.pendingListData = [];
          }
        } else {
          this.pendingListData = this.orderTaskHand(
              result.meta.orderDealTasks,
              item
          );
        }
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: "error",
        });
      }
    },
    // 待处理list处理
    orderTaskHand(list, CTOInfo) {
      let content = [];
      list.map((item) => {
        let width = "";
        let top = "";
        if (item.taskUrl == "SendAudit" || item.taskUrl == "Audit") {
          width = "50%";
          top = "15vh";
        } else {
          width = "98%";
          top = "3vh";
        }
        content.push({
          title: item.taskName,
          ODKInfo: item,
          CTOInfo: CTOInfo,
          content: item.taskUrl,
          width: width,
          top: top,
        });
      });
      return content;
    },
    itemRadioChange(e) {
      localStorage.setItem("radionSelectedcustormer", JSON.stringify(e));
      // this.$emit("selectedCustomer", e);
    },
    // 生成报价单
    async saveGenerateQuotation(item) {
      let base = {
            userId: this.user.staffId,
            oneOrmany: "many",
          },
          { taskId, orderAuditId } = item.ODKInfo,
          { custId, custSoNumber, custOrderId, prodOfferId } = item.CTOInfo;
      // 临时写死prodOfferId MSTP,回头删掉
      prodOfferId = "10010021";

      let offerType = this.getOfferType(prodOfferId);
      let allParams = {
        custId,
        custSoNumber,
        custOrderId,
        taskId,
        prodOfferId,
        offerType,
        orderAuditId,
        ...base,
      };

      const result = await CustOrderService.saveGenerateQuotation(allParams);
      // 查看报价单
      try {
        if (result.meta.resultCode == 0) {
          // 生成报价单成功
          this.$message({
            type: "success",
            message: "保存成功!",
          });
          //直接打开报价单详情
          this.isContent = item;
          this.isContent.CTOInfo = {
            offerType,
            prodOfferId,
            ...this.isContent.CTOInfo,
          };
          this.isContent.content = "GenerateQuotations";
          this.pendItemVisible = true;
        } else {
          this.$message({
            showClose: true,
            message: result.meta.resultMsg,
            type: "warn",
          });
        }
      } catch {
        this.$message({
          showClose: true,
          message: "code:" + result.meta.resultCode + "  msg:" + result.meta.resultMsg,
          type: "error",
        });
      }
    },
    // 生成决算单
    async saveBalanceBill(item) {
      let base = {
            staffId: this.user.staffId + "",
            staffName: this.user.staffName + "",
            oneOrmany: "many",
            userId: this.user.staffId + ""
          },
          { taskId, orderAuditId } = item.ODKInfo,
          { custId, orderItemIds, custSoNumber, custOrderId, batchNbr } =
              item.CTOInfo;
      const result = await CustOrderService.callBalanceBill({
        custId,
        orderItemIds,
        custSoNumber,
        custOrderId,
        batchNbr,
        taskId,
        orderAuditId,
        ...base,
      });
      if (result.meta.resultCode == 0) {
        // 生成决算单成功
        this.open('生成决算单成功！');
        this.isContent = [];
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: "error",
        });
      }

    },
    // 生成预收费单
    async saveGenerateBill(item) {
      let base = {
            userId: this.user.staffId + "",
            oneOrmany: "many",
          },
          { taskId, orderAuditId } = item.ODKInfo,
          { custId, orderItemIds, custSoNumber, custOrderId, prodOfferId } =
              item.CTOInfo;
      // 临时写死prodOfferId MSTP,回头删掉
      prodOfferId = "10010021";
      let offerType = this.getOfferType(prodOfferId);
      let allParams = {
        custId,
        custSoNumber,
        orderItemIds,
        custOrderId,
        taskId,
        prodOfferId,
        offerType,
        orderAuditId,
        ...base,
      };

      const result = await CustOrderService.saveGenerateBill(allParams);
      try {
        if (result.meta.resultCode == 0) {
          // 生成收费单成功
          this.open('生成收费单成功！');
          this.isContent = [];
        } else {
          this.$message({
            showClose: true,
            message: result.meta.resultMsg,
            type: "error",
          });
        }
      } catch {
        this.$message({
          showClose: true,
          message: "code:" + result.code + "  msg:" + result.msg,
          type: "error",
        });
      }
    },
    isSameFun(arr1, arr2) {
      let t = false;
      arr1.forEach((item1) => {
        arr2.forEach((item2) => {
          if (item1 == item2) {
            t = true;
          }
        });
      });
      return t;
    },
    getOfferType(prodOfferId) {
      let gjyw = ["10010059", "10010060", "10010012", "10010013"],
          dkyw = [
            "10010064",
            "10010066",
            "10010019",
            "10010021",
            "10010022",
            "10010023",
            "10010024",
            "10010073",
            "10010058",
            "10010111",
            "12000201",
            "24011235",
          ],
          prodOfferIdArr = prodOfferId.split(","),
          offerType = null;
      if (this.isSameFun(prodOfferIdArr, gjyw)) {
        offerType = "gjyw";
      } else if (this.isSameFun(prodOfferIdArr, dkyw)) {
        offerType = "dkyw";
      } else if (offerType) {
        offerType = "other";
      }
      return offerType;
    },
    // 转订单
    async convertOrder(ODKInfo, CTOInfo) {
      let userId = this.user.staffId;
      let { orderAuditId, taskId } = ODKInfo;
      let { custId, custSoNumber, custOrderId, orderItemId } = CTOInfo;
      let allParams = {
        userId,
        taskId,
        custOrderId,
        custSoNumber,
        orderAuditId,
        orderItemId,
        custId,
        ...{ paramType: "ORDER" },
      };

      const result = await CustOrderService.handelConvertOrder(allParams);
      try {
        if (result.meta.resultCode == 0) {
          // 转订单成功
          this.open('转订单成功！');
          this.qryPendingOrderList({ ...this.conditions });
        } else {
          this.$message({
            showClose: true,
            message: result.meta.resultMsg,
            type: "error",
          });
        }
      } catch {
        this.$message({
          showClose: true,
          message: "code:" + result.code + "  msg:" + result.msg,
          type: "error",
        });
      }
    },
    openLookPendDialog(item2, CTOInfo) {
      // 临时
      let prodOfferId = "10010021";
      let offerType = this.getOfferType(prodOfferId);
      this.isContent = {
        title: item2.title,
        ODKInfo: item2,
        CTOInfo: {offerType,prodOfferId,...CTOInfo},
        content: item2.content,
        width: "98%",
        top: "3vh",
      };
      //附件菜单单独处理下数据
      if (item2.content == "OrderFiles") {
        this.isContent.width="56%";
        this.isContent.CTOInfo=[{offerType,prodOfferId,...CTOInfo}]
        this.isContent.ODKInfo.sysource = "1";
      }
      this.pendItemVisible = true;
    },
    // 弹窗判断
    openPendDialog(item2) {
      if (item2.content == "ConvertOrder") {
        // 转订单
        this.convertOrder(item2.ODKInfo, item2.CTOInfo);
      } else if (item2.content == "toSalesDeal") {
        // 转销售品处理
        this.$emit("showsale", item2.CTOInfo);
        if(this.showSaleInfo){
          this.showSaleInfo(item2.CTOInfo);
        }
        // } else if (item2.content == "/order/taskDeal!balanceBill.action") {
      } else if(item2.content == "BalanceBill") {
        // 生成决算单
        this.saveBalanceBill(item2);
      }else if (item2.content == "GenerateQuotations") {
        // 生成报价单
        this.saveGenerateQuotation(item2);
      } else if (item2.content == "generateBill") {
        // 生成收费单
        this.saveGenerateBill(item2);
      } else if (item2.content == "AcctBalanceBill" || item2.content == "GenerateBillList" || item2.content == "sendAuditDemandOrder") {
        // 临时写死prodOfferId MSTP,回头删掉
        let prodOfferId = "10010021";
        let offerType = this.getOfferType(prodOfferId);
        this.isContent = item2;
        this.isContent.CTOInfo = {
          offerType,
          prodOfferId,
          ...this.isContent.CTOInfo,
        };
        if(item2.content == "sendAuditDemandOrder"){ this.isContent.content = "GenerateQuotations"; }
        this.pendItemVisible = true;
      } else {
        this.isContent = item2;
        this.pendItemVisible = true;
      }
      this.$store.commit('orders/SET_LIST_LOADING',false);
    },
    // 打开转订单弹窗
    open(msg) {
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        type: "success",
        center: true,
      });
    },
    // 打开外层工单待处理任务时锚点判断
    async anchorFun(item) {
      // if(item.CTOInfo.statusCd=='401498'&&item.ODKInfo.taskId!='TACHE10020001'){
      //   this.$message({
      //     message: '退单中的销售品,除审核退单其他都不能操作',
      //     type: 'warning'
      //   });
      //   return false;
      // }
      this.$store.commit('orders/SET_LIST_LOADING',true);
      /**
       * 参数说明
       * ODKInfo:{
          orderAuditId: "4125"
          orderSoNbr: "JT202100007935"
          tacheId: "TACHE0007"
          taskId: "TACHE00070001"
          taskName: "生成收费单"
          taskUrl: "generateBill"
        };
       CTOInfo:{
          acceptLanId: "500181403"
          acceptRegionId: "500181403"
          acceptTime: "2021-05-30 15:06:34"
          audDate: "2021-05-30 15:06:55"
          audFirstId: "1"
          audFirstName: "admin"
          batchNbr: "0"
          channelId: "10"
          createDate: "2021-05-30 15:06:34"
          createOrgId: "1944640"
          createPost: "0"
          createStaff: "1"
          custId: "80"
          custManagerName: "系统管理员"
          custName: "邯郸美的制冷设备有限公司"
          custOrderId: "14280"
          custOrderType: "50200001"
          custSoNumber: "JT202100007935"
          customerInteractionEventId: "14280"
          elecFile: "未上传"
          groupNbr: ""
          handleOrgId: "1944640"
          oneSubFlag: "0"
          operType: "1000"
          orderAuditId: "4125"
          orderSource: "1000"
          orderSourceId: "10000"
          staffName: "系统管理员"
          statusCd: "200000"
          statusDate: "2021-05-30 15:06:34"
          sysSource: "1000"
          verNum: "1"
        }
       **/
      if(!item.hasOwnProperty('ODKInfo')){
        this.openPendDialog(item);
        return
      }
      //待处理工单规则埋点
      var ruleParam = [
        {
          PUB_REQ: {
            TYPE: "GOVCRM.TASK.taskLevel",
          },
          // CUST: {
          //   CUST_ID: item.CTOInfo.custId+"",
          // },
          // ORDCOMMON: {
          //   STAFF_ID: this.user.staffId+"",
          //   ORG_ID: this.user.orgId+"",
          // },
          // ORDERTASK: {
          //   TASK_ID: item.ODKInfo.taskId+"",
          //   TACHE_ID: item.ODKInfo.tacheId+"",
          // },
          // ORDER: {
          //   CUST_SO_NUMBER: item.CTOInfo.custSoNumber+"",
          //   BATCH_NBR: item.CTOInfo.batchNbr+"",
          //   CUST_ORDER_TYPE: item.CTOInfo.custOrderType+"",
          // },
          ORDER_AUDIT_CHECK: {
            TASK_ID: item.ODKInfo.taskId+"",
            CUST_SO_NUMBER: item.CTOInfo.custSoNumber+"",
            BATCH_NO: item.CTOInfo.batchNbr+"",
            CUST_ORDER_TYPE: item.CTOInfo.custOrderType+"",
            TASK_ID2: item.ODKInfo.taskId+"",
            CUST_ID: item.CTOInfo.custId+"",
            //工单级别可能有多个，传空
            PRODUCT_ID: ''
          }
        }
      ];
      //调用规则平台
      const result = await OrderService.rulePlatfromCheck(ruleParam);
      let ruleCode = result.code;
      let ruleMsg = result.msg;
      //直接通过校验
      if (ruleCode == 0) {
        //继续之前逻辑
        this.openPendDialog(item);
      } else {
        //校验结果有警告或者拒绝，弹窗提示
        //图标样式
        let iconType = "warning";
        if (ruleCode == 2) {
          iconType = "error";
        }
        this.$confirm(ruleMsg, "提示", {
          confirmButtonText: "确定",
          type: iconType,
        })
        .then(() => {
          //不是拒绝执行（提醒或异常）
          if (ruleCode != 2) {
            //继续之前逻辑
            this.openPendDialog(item);
          }else{
            this.$store.commit('orders/SET_LIST_LOADING',false);
          }
        })
        .catch(() => {
          this.$store.commit('orders/SET_LIST_LOADING',false);
        });
      }
    },
    findMessage(id) {
      this.$emit("findMessage", id);
    },
  },
};
